/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import Message.LoginMessage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author liyuchen
 */
public class MainControl extends Thread{
    // The server socket.
    public static ServerSocket  serverSocket = null;
    // The client socket.
    public static Socket clientSocket = null;
    
    public static final int maxClientsCount = 20;
    public static final ClientThread[] threads = new ClientThread[maxClientsCount];
    
    @Override
    public void run(){
        
        int portNumber = 7799;
        
        try {
            serverSocket = new ServerSocket (portNumber);
        } catch (IOException e) {
            System.out.println(e);
        }
        
        File userFolder = new File("users");
        if(!userFolder.exists()) userFolder.mkdir();
        
        while(true){
            try{
                clientSocket = serverSocket.accept();
                InputStream is = clientSocket.getInputStream();  
                ObjectInputStream ois = new ObjectInputStream(is); 
                LoginMessage loginMsn = (LoginMessage)ois.readObject();
                
                int i = 0;
                for(i = 0; i < maxClientsCount; i++){
                    if (threads[i] == null) {
                        (threads[i] = new ClientThread(clientSocket,loginMsn)).start();
                        break;
                    }
                }
                if(i == maxClientsCount){
                    loginMsn.SetLoginResult(false,1);
                    OutputStream os = clientSocket.getOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(os); 
                    oos.writeObject(loginMsn);
                }
            }catch (Exception e) {
                System.out.println(e);
                System.exit(1);
            }
        }
    }
    
    
}
